package de.gwtprime.server.servlets.cron;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import de.gwtprime.server.model.Order;
import de.gwtprime.server.util.RPCClient;
import de.gwtprime.shared.util.AppUtilsShared;

/**
 * @author jan
 *
 */
public class ProcessOrdersServlet extends HttpServlet{

	/**
	 * Serial version ID
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * Logger
	 */
	private static Logger logger = Logger.getLogger(ProcessOrdersServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
 		for(Order order : Order.loadUnprocessedOrders()){
			
			// If private withdraw address is set -> user wants to withdraw to private address
			if(!AppUtilsShared.isNullOrEmpty(order.getPrivateWithdrawAddress())){
				try {
					order.setProcessed(true);
					order.persist();
					RPCClient.getInstance().sendCoinsToAddress(
							order.getPrivateWithdrawAddress(), order.getAmount());
					logger.info(String.format("Successfully processed order '%s': Sending '%s' coins to address: '%s': ",
							order.getId(), order.getPrivateWithdrawAddress(), order.getAmount()));
				} catch (Exception e) {
					logger.error(String.format("Could not process order '%s': Sending '%s' coins to address: '%s': ",
							order.getId(), order.getPrivateWithdrawAddress(), order.getAmount()) , e);
				}
				
			}
		}
 		
 		resp.getWriter().println("done");
	}
}
